using Gateway.Common.Cache;
using Gateway.IQuery.Cache;
using Gateway.IQuery.Cache.Request;
using Gateway.IQuery.Cache.Result;
using Aurora.Redis;

namespace Gateway.Query;

/// <summary>
/// 缓存查询
/// </summary>
public class CacheQuery : ICacheQuery
{
    private readonly IRedisCache _redisCache;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="redisCache"></param>
    public CacheQuery(IRedisCache redisCache)
    {
        _redisCache = redisCache;
    }

    /// <summary>
    /// 获取缓存的列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<CacheDetailResult>> GetList()
    {
        // var list = new List<CacheDetailResult>();
        // var currentAssembly = Assembly.GetEntryAssembly();
        // List<Assembly> assemblies = new List<Assembly>();
        var data = await _redisCache.GetKeys(CacheKeys.CACHE_PREFIX + "*");
        return data?.Select(p => new CacheDetailResult()
        {
            Name = p
        }).ToList();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<List<CacheDetailResult>> GetDetailList(CacheDetailRequest request)
    {
        if (request.Value.EndsWith(":"))
        {
            request.Value += "*";
        }

        var data = await _redisCache.GetKeys(request.Value);
        return data?.Select(p => new CacheDetailResult()
        {
            Name = p
        }).ToList();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public Task<CacheDetailResult> GetDetail(CacheDetailRequest request)
    {
        var data = _redisCache.Get<string>(request.Value);
        return Task.FromResult(new CacheDetailResult()
        {
            Name = request.Value,
            Value = data
        });
    }
}